var WxParse = require('../../../wxParse/wxParse.js');
var baseURL = getApp().globalData.baseURL;
var companyUtil = require('../companyUtil/companyUtil.js');
var baseURLtest = getApp().globalData.baseURLtest;
var util = require("../../../utils/util.js");

Page({
  /**
   * 页面的初始数据
   */
  data: {

    campusTable: "campus_table", //招聘简章激活状态
    jobTable: "classify_table", //职位列表激活状态
    campusListDiv: "message_list", //招聘简章页显示
    jobListDiv: "job_list", //职位列表页显示

    isLogin: false,
    haveInfo: false,

    companyId: "",
    company: null,
    companyJobs: [],
    myApplications: [],

    myOnlineResumes: [],
    myVideoResumes: [],
    videoResumeSelectedId: "",
    onlineResumeSelectedId: "",

    translate: "", //简历挑选框的动画
    showResumeSelect: false,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this
    _this.setData({
      companyId: options.companyId
    })
    wx.showLoading({
      title: '',
    })
    //获取并设置用户详细信息,获取数据
    _this.getAndSetloginInfo().then((res) => {
      WxParse.wxParse('introduce', 'html', "正在加载中...", _this, 5);
      if (_this.data.haveInfo) {
        _this.getMyOnlineResume();
        _this.getMyVideoResume();
      }
      _this.getCompanyDetail().then((res) => {
        _this.getApplicationByUserProfile();
        wx.hideLoading();
      });
    })
    wx.setNavigationBarTitle({
      title: '宣讲会与职位',
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(e) {
    return {
      title: "香樟明人-宣讲会",
      path: "pages/company/company_work/company_work?companyId=" + this.data.companyId
    }
  },

  /**
   * 监听用户下拉动作
   */
  onPullDownRefresh: function(e) {
    var _this = this;
    //获取并设置用户详细信息,获取数据
    wx.showLoading({
      title: '',
    })
    this.getAndSetloginInfo().then((res) => {
      WxParse.wxParse('introduce', 'html', "正在加载中...", _this, 5);
      if (_this.data.haveInfo) {
        _this.getMyOnlineResume();
        _this.getMyVideoResume();
      }
      _this.getCompanyDetail().then(() => {
        _this.getApplicationByUserProfile();
        wx.stopPullDownRefresh();
        wx.hideLoading();
      });
    })
  },

  /**
   * 监听页面显示
   */
  onShow: function(e) {
  },

  /**
   * 显示招聘简章（campus）
   */
  showCampus: function(res) {
    var that = this;
    that.setData({
      campusTable: "campus_table",
      jobTable: "classify_table",
      campusListDiv: "message_list",
      jobListDiv: "job_list"
    })

  },

  /**
   * 显示职位列表
   */
  showJob: function(res) {
    var that = this;
    that.setData({
      campusTable: "classify_table",
      jobTable: "job_table",
      campusListDiv: "campus_list",
      jobListDiv: "message_list"
    })

  },

  //根据companyId获取公司详情
  getCompanyDetail: function(e) {
    var _this = this;
    return new Promise(function(resolve, reject) {
      var companyId = _this.data.companyId;
      companyUtil.getCompanyDetailByCompanyId(companyId).then((res) => {
        var gotCompany = res;
        _this.setData({
          company: gotCompany
        })
        WxParse.wxParse('introduce', 'html', gotCompany.introduce, _this, 5);
        companyUtil.listPositionsByCompanyName(res.fullName).then((res) => {
          _this.setData({
            companyJobs: res
          })
          resolve();
        })
      })
    })
  },

  /**
   * 请求用户的投递列表
   */
  getApplicationByUserProfile: function(e) {
    var _this = this;
    return new Promise(function(resolve, reject) {
      if (_this.data.haveInfo) {
        wx.request({
          url: baseURLtest + 'application/' + getApp().globalData.userProfile.id,
          method: "GET",
          header: getApp().globalData.header,
          data: {},
          success: function(res) {
            if (res.statusCode == 200) {
              _this.setData({
                myApplications: res.data,
              })
            } else {
              console.log(res);
              util.go404Page(res.statusCode, res.data);
            }
          },
          fail: function(res) {
            console.log(res);
            util.go404Page(res.statusCode, res.data);
          },
          complete: function(res) {
            resolve();
          }
        })
      } else {
        resolve();
      }
    })
  },

  /**
   * 请求用户的在线简历
   */
  getMyOnlineResume: function(res) {
    var _this = this;
    return new Promise(function(resolve, reject) {
      wx.request({
        url: baseURLtest + 'online_resume/myOnlineResumes?userProfileId=' + getApp().globalData.userProfile.id,
        method: "GET",
        header: getApp().globalData.header,
        data: {},
        success: function(res) {
          if (res.statusCode == 200) {
            var myOnlineResumes = res.data;
            for (var j = 0; j < myOnlineResumes.length; j++) {
              myOnlineResumes[j].isSelected = false;
            }
            _this.setData({
              myOnlineResumes: myOnlineResumes,
            })
          } else {
            console.log(res);
            util.go404Page(res.statusCode, res.data);
          }
        },
        fail: function(res) {
          console.log(res);
          util.go404Page(res.statusCode, res.data);
        },
        complete: function(res) {
          resolve();
        }
      })
    })
  },

  /**
   * 请求用户的视频简历
   */
  getMyVideoResume: function(res) {
    var _this = this;
    return new Promise(function(resolve, reject) {
      wx.request({
        url: baseURLtest + 'video_resume/my_videos?userProfileId=' + getApp().globalData.userProfile.id,
        method: "GET",
        header: getApp().globalData.header,
        data: {},
        success: function(res) {
          if (res.statusCode == 200) {
            var myVideoResumes = res.data;
            for (var i = 0; i < myVideoResumes; i++) {
              myVideoResumes[i].isSelected = false;
            }
            _this.setData({
              myVideoResumes: myVideoResumes,
            })
          } else {
            console.log(res);
            util.go404Page(res.statusCode, res.data);
          }
        },
        fail: function(res) {
          console.log(res);
          util.go404Page(res.statusCode, res.data);
        },
        complete: function(res) {
          resolve();
        }
      })
    })
  },

  //点击网申投递，显示简历的挑选框
  applicating: function(e) {
    //判断登录状态和信息状态
    var _this = this;
    if (!_this.data.isLogin) { //未登录
      wx.showModal({
        title: '提示',
        content: '你还没登录哦',
        success: function(res) {
          if (res.confirm) {
            //用户点击确认
            wx.switchTab({
              url: '/pages/my/my',
            })
          } else if (res.cancel) {
            //用户点击取消
          }
        }
      })
    } else if (_this.data.isLogin) { //已登录
      var haveInfo = _this.data.haveInfo;
      if (!_this.data.haveInfo) {
        wx.showModal({
          title: '提示',
          content: '你还没填写个人简介哦',
          success: function(res) {
            if (res.confirm) {
              //用户点击确认
              wx.switchTab({
                url: '/pages/my/user_detail/detail',
              })
            } else if (res.cancel) {
              //用户点击取消
            }
          }
        })
      } else if (_this.data.haveInfo) {
        if (_this.data.myOnlineResumes.length == 0) {
          wx.showToast({
            title: '您还没有简历，请制作一份新简历后再来投递哦',
            icon: "none",
          })
          return;
        }
        //用户已登录并且已经填了详细信息
        //判断此工作是否投递
        var myApplications = _this.data.myApplications;
        var companyName = e.currentTarget.dataset.companyName;
        var name = e.currentTarget.dataset.name;
        for (var i = 0; i < myApplications.length; i++) {
          if (myApplications[i].positionName == name && myApplications[i].companyName == companyName) {
            //此工作已投递
            wx.showToast({
              title: '此职位您已投递，请不要重复投递简历',
              icon: "none",
            })
            return;
          }
        }
        //判断投递次数是否到达5次
        if (myApplications.length >= 5) {
          wx.showToast({
            title: '您已投递5个职位，不能再投递了哦',
            icon: "none",
          })
          return;
        }
        //显示简历挑选框
        if (this.data.showResumeSelect) {
          this.setData({
            translate: 'transform: translateX(-440rpx)',
            showResumeSelect: false,
          })
          setTimeout(function() {
            _this.setData({
              translate: 'transform: translateX(440rpx)',
              showResumeSelect: true,
            })
          }, 500)
        } else {
          this.setData({
            translate: 'transform: translateX(440rpx)',
            showResumeSelect: true,
          })
        }
        this.setData({
          companyName: e.currentTarget.dataset.companyName,
          name: e.currentTarget.dataset.name,
          videoDelivered: (e.currentTarget.dataset.isVideoDelivered) != null ? e.currentTarget.dataset.isVideoDelivered: false,
        })
      }
    }
  },

  /**
   * 点击一项在线简历
   */
  onlineResumeSelected: function(e) {
    var resumeId = e.currentTarget.dataset.resumeId;
    var resumes = [];
    resumes = this.data.myOnlineResumes;
    for (var i = 0; i < resumes.length; i++) {
      if (resumes[i].id == resumeId) {
        resumes[i].isSelected = true;
        this.setData({
          onlineResumeSelectedId: resumes[i].id,
        })
      } else {
        resumes[i].isSelected = false;
      }
    }
    this.setData({
      myOnlineResumes: resumes,
    })
  },

  /**
   * 点击一项视频简历
   */
  videoResumeSelected: function(e) {
    //判断这个公司是否接受视频简历
    if (this.data.videoDelivered != false) {
      var resumeId = e.currentTarget.dataset.resumeId;
      var resumes = [];
      resumes = this.data.myVideoResumes;
      for (var i = 0; i < resumes.length; i++) {
        if (resumes[i].id == resumeId) {
          resumes[i].isSelected = true;
          this.setData({
            videoResumeSelectedId: resumes[i].id,
          })
        } else {
          resumes[i].isSelected = false;
        }
      }
      this.setData({
        myVideoResumes: resumes,
      })
    }else{
      wx.showToast({
        title: '此公司不支持视频简历，请投递在线简历哦！',
        icon: "none"
      })
    }
  },

  /**
   * 点击确认投递
   */
  confirmToApplicate: function(res) {
    var _this = this;
    var userProfileId = getApp().globalData.userProfile.id;
    var companyName = this.data.companyName;
    var name = this.data.name;
    wx.showModal({
      title: '提示',
      content: '每个同学最多只能投递5个岗位哦，确认投递？',
      success: function(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '正在投递中',
          })
          var onlineResumeId = _this.data.onlineResumeSelectedId;
          var videoResumeId = _this.data.videoResumeSelectedId;
          if (onlineResumeId.length == 0) {
            wx.showToast({
              title: '至少选择一个在线简历才能投递哦',
              icon: "none"
            })
            return;
          }
          var param = {
            userProfileId: userProfileId,
            positionName: name,
            companyName: companyName,
            onlineResumeId: onlineResumeId,
            videoResumeId: videoResumeId
          }
          wx.request({
            method: "POST",
            url: baseURLtest + 'application',
            data: param,
            header: getApp().globalData.header,
            success: function(res) {
              if (res.statusCode == 200) {
                wx.hideLoading();
                wx.showToast({
                  title: '投递成功，并请及时前往官网完成在线测评',
                  icon: "none",
                  duration: 4000,
                })
                var myApplications = _this.data.myApplications;
                myApplications.push(res.data);
                _this.setData({
                  myApplications: myApplications,
                })
              } else {
                console.log(res);
                util.go404Page(res.statusCode, res.data);
              }
            },
            fail: function(res) {
              console.log(res);
              util.go404Page(res.statusCode, res.data);
            },
            complete: function(res) {
              _this.setData({
                translate: 'transform: translateX(-440rpx)',
                showResumeSelect: false,
              })
            }
          })
        } else if (res.cancel) {
          //用户点击取消
        }
      }
    })
  },

  //获取并设置用户登录状态与信息
  getAndSetloginInfo: function(e) {
    var _this = this;
    return new Promise(function(resolve, reject) {
      wx.showNavigationBarLoading();
      wx.getStorage({
        key: 'userLogin',
        success: function(res) {
          //设置登录状态
          _this.setData({
            isLogin: true
          })
          //设置全局用户数据
          getApp().globalData.userData = res.data;
          //请求详细信息,设置信息状态
          var userProfileId = getApp().globalData.userProfile.id;
          companyUtil.getUserProfile(userProfileId).then((res) => {
            _this.setData({
              haveInfo: res ? true : false
            })
            getApp().globalData.userProfile = res;
            wx.hideNavigationBarLoading();
            resolve();
          })
        },
        fail: function(res) {
          _this.setData({
            isLogin: false
          })
          wx.hideNavigationBarLoading();
          resolve();
        },
      })
    })
  },

  //取消简历挑选
  resumeSelectQuit: function(e) {
    this.setData({
      translate: 'transform: translateX(-440rpx)',
      showResumeSelect: false,
    })
  },


})